package com.gztms.handler;

import com.alibaba.fastjson.JSON;
import com.gztms.enums.AppCodeEnum;
import com.gztms.utils.ResultUtil;
import com.gztms.utils.WebUtils;
import lombok.val;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Zoey
 * @date 2023/3/15 16:29
 * @Description 自定义异常处理
 **/
@Component
public class AuthenticationEntryPointImpl implements org.springframework.security.web.AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        // 处理异常
        e.printStackTrace();
        ResultUtil resultUtil = null;
        if (e instanceof BadCredentialsException) {
            resultUtil = new ResultUtil(AppCodeEnum.LOGIN_ERROR.getCode(),AppCodeEnum.LOGIN_ERROR.getMsg());
//            resultUtil = ResultUtil.errorResult(AppCodeEnum.LOGIN_ERROR.getCode(), e.getMessage());
        }else if (e instanceof InsufficientAuthenticationException) {
            resultUtil = ResultUtil.errorResult(AppCodeEnum.NEED_LOGIN);
        }else {
            resultUtil = ResultUtil.errorResult(AppCodeEnum.SYSTEM_ERROR,"用户认证或授权失败");
        }
        String json = JSON.toJSONString(resultUtil);
        WebUtils.renderString(httpServletResponse,json);
    }
}
